import { useRef, useState, useEffect, RefObject } from 'react'
import { Modal, Form, Input, Button, Select, Switch, FormInstance, message } from 'antd';
import style from './index.module.less'
import Upload from '@components/upload'
import { PDFTemplateSchema } from '@src/components/schema/pdf'
import { download } from '@js/downloadRename'
import { modifyRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool';
const { Item } = Form
const { Option } = Select

function renderDownload (d: PDFTemplateSchema | null) {
  if (!d) {
    return null
  }
  const p = d.docx_path
  const t = d.title
  if (p && t) {
    return (
      <Item label='模板下载'>
        <a className={style.link} onClick={() => download(p, t)}>{t}</a>
      </Item>
    )
  }
}

function initData (formRef: RefObject<FormInstance>, data: PDFTemplateSchema) {
  const c = formRef.current
  if (!c) {
    return setTimeout(() => {
      initData(formRef, data)
    }, 100)
  }
  const keys = Object.keys(data)
  const d: PDFTemplateSchema = {} as PDFTemplateSchema
  keys.forEach(k => {
    d[k] = data[k] ? data[k] : undefined
  })
  // d.user_define = d.user_define === 1
  c.setFieldsValue(d)
}


async function onFinish (d: PDFTemplateSchema, justyModifyFile: boolean,  hide: () => void, refreshFn: () => void){
  if (d.id) {
    modifyHandle(d, justyModifyFile, () => {
      hide()
      setTimeout(() => {
        refreshFn()
      })
    })
  } else {
    addRequest(d, () => {
      hide()
      setTimeout(() => {
        refreshFn()
      })
    })
  }
}

// 修改文档请求
async function modifyHandle (d: PDFTemplateSchema, justyModifyFile: boolean, callback: () => void) {
  const hide = message.loading('提交中', 120)
  const formData = new FormData()
  let url = '/api/commission/file_template_update/'
  if (d.temp_sign_type) {
    formData.append('temp_sign_type', d.temp_sign_type)
  }
  if (d.title) {
    formData.append('title', d.title)
  }
  if (d.file instanceof Array) {
    const f = d.file[0]
    formData.append('file', f.originFileObj)
  }
  // if (d.user_define !== undefined) {
  //   formData.append('user_define', d.user_define ? '1 ': '2')
  // }
  if (justyModifyFile) {
    url = '/api/commission/file_template_update_file/'
  }
  const [e] = await awaitWrap(modifyRequest(`${url}${d.id}`, formData))
  hide()
  if (e === null) {
    callback()
  }
}

// 添加文档请求
async function addRequest (d: PDFTemplateSchema, callback: () => void) {
  const hide = message.loading('提交中', 120)
  const formData = new FormData()
  formData.append('title', d.title)
  formData.append('temp_sign_type', d.temp_sign_type)
  if (d.file instanceof Array) {
    const f = d.file[0]
    formData.append('file', f.originFileObj)
  }
  // formData.append('user_define', d.user_define ? '1' : '2')
  const [e] = await awaitWrap(modifyRequest('/api/commission/file_template', formData))
  hide()
  if (e === null) {
    callback()
  }
}

interface Props {
  data: PDFTemplateSchema | null
  justyModifyFile: boolean
  visible: boolean
  hide: () => void
  refreshFn: () => void
}

function Main ({ justyModifyFile, data, visible, hide, refreshFn }: Props) {
  const formRef = useRef<FormInstance>(null)
  const [isFileRequire, setIsFileRequire] = useState(false)
  const [title, setTitle] = useState('添加文书模板')
  useEffect(() => {
    if (data !== null) {
      const hasId = typeof data.id === 'string' && data.id.length > 0
      setIsFileRequire(!hasId)
      setTitle(hasId ? '修改文书模板' : '添加文书模板')
    }
  }, [data])
  useEffect(() => {
    const c = formRef.current
    if (c !== null) {
      if (visible) {
        data !== null && initData(formRef, data)
      } else {
        c.resetFields()
      }
    }
  }, [visible, data])
  return (
    <Modal
        title={title}
        visible={visible}
        onOk={() => formRef.current?.submit()}
        onCancel={() => hide()}
        maskClosable={false}
      >
      <Form name='document-manage' labelCol={{ flex: '100px' }} ref={formRef} onFinish={(d: PDFTemplateSchema) => onFinish(d, justyModifyFile, hide, refreshFn)}>
        <Item noStyle name='id'><span /></Item>
        {renderDownload(data)}
        {!justyModifyFile ? (
          <>
            {/* <Item name='user_define' label='是否呈批' valuePropName='checked'>
              <Switch checkedChildren='是' unCheckedChildren='否' />
            </Item> */}
            <Item name='title' label='文书名称' rules={[{ required: true, message: '文书名称不能为空' }]}>
              <Input placeholder='请输入文书名称' />
            </Item>
            <Item name='temp_sign_type' label='文书类型' rules={[{ required: true, message: '文书类型不能为空' }]}>
              <Select placeholder='请选择文书类型'>
                <Option value='location'>位置签名</Option>
                <Option value='keyword'>关键字签名</Option>
              </Select>
            </Item>
          </>
        ) : null}
        <Item name='file' label='文件' rules={[{ required: isFileRequire, message: '文件不能为空' }]}>
          <Upload accept='.docx' maxLength={1} />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
